<template>
    <div>
        <el-affix :offset="50" style="margin-left: 1rem;">
            <el-button type="primary" @click="saveContent()">保存</el-button>
        </el-affix>

        <div class="essay-contain" ref="vditorContainerRef" style="height: 51.1rem;"></div>
    </div>
    <!-- <button @click="getContent">获取内容</button> -->
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import Vditor from 'vditor'
import 'vditor/dist/index.css'
import { useRoute } from 'vue-router';
import { getOneArticle, saveArticle } from '../utils/axios';
import { ElMessage } from 'element-plus'
import Cookies from 'js-cookie';
const { query } = useRoute();

let router = useRoute()
//下面是定义文章的内容
const vditorContainerRef = ref(null)
let vditorInstance
let content = ref('')


onMounted(() => {
    if (Cookies.get('cookie-jwt') == '') {
        router.push('/login')
    } else {
        getOneArticle(query.id).then(success => {

            if (success.code == 300) {
                router.push('/login')
            }

            content.value = success.data.data.data.content
            //拿到数据的时候再去加载
            vditorInstance = new Vditor(vditorContainerRef.value, {
                mode: 'wysiwyg', // 使用所见即所得模式
                height: '51.1rem',
                toolbarConfig: {
                    pin: true
                },
                cache: {
                    enable: false
                },
                after() {
                    vditorInstance.setValue(content.value);
                    console.log("成功2");
                }
            })

        }).catch(error => {
            console.log("请求错误" + error);
        })
    }

})

function saveContent() {

    const content = vditorInstance.getValue()
    // console.log(query.id);
    saveArticle(query.id, content).then(s => {

        if (s.data.code == 200) {
            ElMessage({
                message: '保存成功',
                type: 'success',
            })
        }

        if (s.data.code == 300) {
            // ElMessage.success('重定向')
            router.push('/login')
        }

    }).catch(e => {
        ElMessage.error('网络错误  保存失败')
    })
}


// const getContent = () => {
//     if (vditorInstance) {
//         const content = vditorInstance.getValue()
//         console.log('获取到的内容：', content)
//         // vditorInstance.setValue("# 世界啊你好");
//     } else {
//         console.error('Vditor 实例尚未初始化')
//     }
// }
</script>

<style scoped>
.essay-contain {
    margin-top: 0.1rem;
}
</style>